<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="100px"
    >
      <el-form-item label="套餐名称" prop="skuName">
        <el-input
          v-model="queryParams.skuName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          @click="openForm('create')"
          v-hasPermi="['train:product-sku:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table ref="tableRef" v-loading="loading" :data="list" @expand-change="handleExpandChange">
      <el-table-column type="expand">
        <template #default="scope">
          <div class="pl-20 pr-3 py-3 bg-gray-100">
            <h2 class="text-xl font-bold mb-3">套餐服务</h2>
            <el-table
              v-loading="skuBindMap[scope.row.id].loading"
              :data="skuBindMap[scope.row.id].list"
              border
            >
              <el-table-column label="名称" align="center" prop="bindTitle" />
              <el-table-column label="状态" align="center" prop="bindType">
                <template #default="bindTypeScope">
                  <el-tag class="ml-2" :type="bindTypeFormatter(bindTypeScope.row.bindType).type">{{
                    bindTypeFormatter(bindTypeScope.row.bindType).text
                  }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="绑定id" align="center" prop="bindId" />
              <!-- <el-table-column label="操作" align="center">
                <template #default="subScope">
                  <el-button
                    link
                    type="primary"
                    @click="openForm('update', subScope.row.id)"
                    v-hasPermi="['train:product-sku-bind:update']"
                  >
                    编辑
                  </el-button>
                  <el-button
                    link
                    type="danger"
                    @click="openForm('update', subScope.row.id)"
                    v-hasPermi="['train:product-sku-bind:delete']"
                  >
                    解绑
                  </el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="套餐缩略图" align="center" prop="picUrl">
        <template #default="scope">
          <el-image
            class="w-20 h-20"
            :src="getOSSURL(scope.row.picUrl)"
            :preview-src-list="[getOSSURL(scope.row.picUrl)]"
            fit="cover"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column label="套餐名称" align="center" prop="skuName" width="180" />
      <el-table-column label="所属班型" align="center" prop="spuName" width="180" />
      <el-table-column
        label="原价"
        align="center"
        prop="originalPrice"
        :formatter="priceFormatter"
      />
      <el-table-column label="售价" align="center" prop="price" :formatter="priceFormatter" />
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column prop="warnStockLimit" label="库存预警" align="center">
        <template #default="scope">
          <el-tag v-if="scope.row.warnStockLimit < scope.row.stock" class="ml-2" type="success">{{
            scope.row.warnStockLimit
          }}</el-tag>
          <el-tag v-else class="ml-2" type="danger">{{ scope.row.warnStockLimit }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag class="ml-2" :type="statusFormatter(scope.row.status).type">{{
            statusFormatter(scope.row.status).text
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="240"
      />
      <el-table-column label="操作" fixed="right" width="240">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openCheckoutConfigForm(scope.row.id)"
            v-hasPermi="['train:product-sku:update']"
          >
            分润配置
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['train:product-sku:update']"
          >
            编辑
          </el-button>
          <el-button link type="primary" @click="tableRef.toggleRowExpansion(scope.row)">
            套餐服务
          </el-button>
          <!-- <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['train:product-sku:delete']"
          >
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <SkuForm ref="formRef" @success="getList" />

  <!-- 分润配置弹窗 -->
  <CheckoutConfigForm ref="checkoutConfigFormRef" @success="getList" />
</template>

<script setup lang="ts" name="ProductSku">
import { dateFormatter } from '@/utils/formatTime'
import * as SkuApi from '@/api/client-mall/product/sku'
import * as SkuBindApi from '@/api/client-mall/product/sku/sku-bind'
import { getOSSURL } from '@/utils/oss'
import { statusDict, bindTypeDict } from './common'
import SkuForm from './sku-form.vue'
import CheckoutConfigForm from './checkout-config-form.vue'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()

const tableRef = ref() // 表格的ref
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  spuId: (router.currentRoute.value.query.spuId as string) || null,
  spuType: 1,
  skuName: null
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const skuBindMap = reactive({}) // sku绑定的服务列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await SkuApi.getPage(queryParams)

    // 初始化sku绑定的服务列表
    data.list.forEach((item: SkuApi.SkuVO) => {
      skuBindMap[item.id] = {
        loading: true,
        list: null
      }
    })

    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

const handleExpandChange = async (row: SkuApi.SkuVO) => {
  if (skuBindMap[row.id].list) return
  skuBindMap[row.id].loading = true
  try {
    const data = await SkuBindApi.listBySkuId(row.id)

    skuBindMap[row.id].list = data
  } finally {
    skuBindMap[row.id].loading = false
  }
}

/** 表格项状态格式化 */
const statusFormatter = (val: number) => {
  const status = statusDict.find((item) => item.value === val)
  return {
    type: status?.type,
    text: status?.label
  }
}

/** 表格项价格式化  分 => 元 */
const priceFormatter = (_row, _column, cellValue, _index) => {
  return cellValue / 100 + '元'
}

/** 绑定类型格式化 */
const bindTypeFormatter = (val: number) => {
  const bindType = bindTypeDict.find((item) => item.value === val)

  return {
    type: bindType?.type,
    text: bindType?.label
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 分润配置 */
const checkoutConfigFormRef = ref()
const openCheckoutConfigForm = (id: string) => {
  checkoutConfigFormRef.value.open(id)
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: string) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: string) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await SkuApi.del(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 初始化 **/
onMounted(getList)
</script>
